#!/usr/bin/env python

import os, sys
from urllib import quote

def listify(dir, level=0, indent='  ', omit=lambda x: False):
    dir = dir.rstrip(os.sep)
    lines = []
    lines.append('%s<ul>' % (indent * level))
    contents = os.listdir(dir)
    contents.sort()
    for item in contents:
        if omit(item):
            continue
        path = ''.join([dir, os.sep, item])
        padding = indent * (level + 1)
        isdir = os.path.isdir(path)
        cls = ''
        if not isdir:
            parts = item.split('.')
            if len(parts) > 1:
                cls = ' class="%s"' % parts[-1]
        lines.append('%s<li>' % padding)
        lines.append('%s<a href="%s"%s>%s</a>' % \
                     (padding + indent, quote(path), cls, item))
        if isdir:
            lines.append(listify(path, level + 2, indent, omit))
        lines.append('%s</li>' % padding)
    lines.append('%s</ul>' % (indent * level))
    return '\n'.join(lines)


if __name__ == '__main__':
    def special(s):
        return (s.startswith('.') or
                s.endswith('~') or
                s.endswith('.pyc'))
    try:
        print listify(sys.argv[1], omit=special)
    except:
        print 'Usage:', sys.argv[0], '<directory>'
        sys.exit(1)
